package com.liucxu.zimuzu.Utils;

import com.liucxu.zimuzu.Consts.Constants;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukanshan on 2016/12/8.
 */

public class ServiceFactory {

    private static ServiceFactory instance;

    public static ServiceFactory GetInstance() {
        synchronized (ServiceFactory.class){
            if (instance == null) {
                instance = new ServiceFactory();
            }
        }
        return instance;
    }

    public <S> S createService(Class<S> serviceClass){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(serviceClass);
    }

    private OkHttpClient getOkHttpClient(){
        OkHttpClient.Builder builder=new OkHttpClient.Builder();
        //设置超时时间以及App拦截器
        builder.connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10,TimeUnit.SECONDS).readTimeout(10,TimeUnit.SECONDS).addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Logger.d("Sending request %s on %s%n%s,body%s",request.url(),chain.connection(),request.headers(),request.body());
                Response originalResponse = chain.proceed(request);
                String body=originalResponse.body().string();
                Logger.json(body);
                return originalResponse.newBuilder()
                        .body(ResponseBody.create(MediaType.parse("UTF-8"), body))
                        .build();
            }
        });
        return builder.build();
    }
}
